package org.gangcai.mac.shop.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
import com.zaaach.citypicker.db.DBManager;
import com.zaaach.citypicker.model.City;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.activity.LoginActivity;
import org.gangcai.mac.shop.activity.MainActivity;
import org.gangcai.mac.shop.activity.TTShopDetailActivity;
import org.gangcai.mac.shop.adapter.AnimationAdapter2;
import org.gangcai.mac.shop.adapter.NinePicturesAdapter;
import org.gangcai.mac.shop.api.AppAPI;
import org.gangcai.mac.shop.bean.CommonResonseBean;
import org.gangcai.mac.shop.bean.HomeDataBean;
import org.gangcai.mac.shop.bean.OrderBean;
import org.gangcai.mac.shop.bean.PostsArticleBaseBean;
import org.gangcai.mac.shop.common.NoScrollGridView;
import org.gangcai.mac.shop.commonutils.ImageLoaderUtils;
import org.gangcai.mac.shop.constants.Constant;
import org.gangcai.mac.shop.implement.MainTabItemListener;
import org.gangcai.mac.shop.manager.RetrofitManageres;
import org.gangcai.mac.shop.oberver.CommonObserver;
import org.gangcai.mac.shop.rxlife.RxFragment;
import org.gangcai.mac.shop.util.ToastUitl;
import org.gangcai.mac.shop.utils.BastiGallery;
import org.gangcai.mac.shop.utils.QiniuUtils;
import org.gangcai.mac.shop.utils.UpLoadImgCallback;
import org.gangcai.mac.shop.utils.UserInfoUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static org.gangcai.mac.shop.constants.Constant.CODE_SUCC;

/**
 * @author HIAPAD
 */
public class PublicPostsFragment extends RxFragment implements View.OnClickListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String TAG = "PublicPostsFragment";
    Unbinder unbinder;
    @BindView(R.id.post_edit_title)
    EditText post_edit_title;
    @BindView(R.id.post_image_layout)
    LinearLayout post_image_layout;
    @BindView(R.id.post_image_gridview)
    NoScrollGridView post_image_gridview;
    @BindView(R.id.post_category_btn)
    Button post_category_btn;
    @BindView(R.id.post_edit_price)
    EditText post_edit_price;
    @BindView(R.id.post_edit_name)
    EditText post_edit_name;
    @BindView(R.id.post_edit_mobile)
    EditText post_edit_mobile;
    @BindView(R.id.post_area_btn)
    Button post_area_btn;
    @BindView(R.id.post_edit_content)
    EditText post_edit_content;
    @BindView(R.id.post_commit_btn)
    Button post_commit_btn;
    private String mParam1;
    private String mParam2;
    private NinePicturesAdapter ninePicturesAdapter;
    private int REQUEST_CODE = 120;
    public static final int RESULT_OK = -1;
    private OptionsPickerView cityCustomOptions;
    private List<City> options1Items = new ArrayList<>();
    private List<ArrayList<City>> options2Items = new ArrayList<>();
    private DBManager dbManager;
    private String uidString;
    private String postTitle;
    private String userName;
    private String phoneNumber;
    private String postPrice;
    private String postRegion;
    private String postArea;
    private String postContent;
    private String photos_url[]=new String[9];

    private static MainTabItemListener mainTabItemListener;

    /**
     * 默认是发布出售
     */
    private String type = "1";

    public PublicPostsFragment() {
        // Required empty public constructor
    }

    public static PublicPostsFragment newInstance(MainTabItemListener mainTabItemListener1,int param1, String param2) {
        PublicPostsFragment fragment = new PublicPostsFragment();
        Bundle args = new Bundle();
        mainTabItemListener = mainTabItemListener1;
        args.putInt( ARG_PARAM1, param1 );
        args.putString( ARG_PARAM2, param2 );
        fragment.setArguments( args );
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        uidString= UserInfoUtils.getAppUserId( getActivity());
        userName= UserInfoUtils.getNickName( getActivity());
        phoneNumber= UserInfoUtils.getPhone( getActivity());
        if (getArguments() != null) {
            type = String.valueOf(getArguments().getInt(ARG_PARAM1));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate( R.layout.activity_post_detail_view, container, false );
        unbinder = ButterKnife.bind( this, view );
        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated( view, savedInstanceState );
        getOptionData();
        ninePicturesAdapter = new NinePicturesAdapter( getActivity(), 9, new NinePicturesAdapter.OnClickAddListener() {
            @Override
            public void onClickAdd(int positin) {
                choosePhoto();
            }
        } );
        post_image_gridview.setAdapter( ninePicturesAdapter );
        if (uidString.equals( "0" )) {
            post_edit_mobile.setText("");
        }else{
            post_edit_name.setText(userName);
            post_edit_mobile.setText(phoneNumber);
        }
        if(type.equals( "1" )){
            post_image_layout.setVisibility( View.VISIBLE );
        }else{
            post_edit_title.setHint( "请输入求购标题" );
            post_edit_name.setHint( "请输入求购联系人" );
            post_edit_content.setHint( "请输入求购成库货源详细信息" );
            post_image_layout.setVisibility( View.GONE );
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        uidString= UserInfoUtils.getAppUserId( getActivity());
        userName= UserInfoUtils.getNickName( getActivity());
        phoneNumber= UserInfoUtils.getPhone( getActivity());
        if (uidString.equals( "0" )) {
            post_edit_mobile.setText("");
        }else{
            post_edit_name.setText(userName);
            post_edit_mobile.setText(phoneNumber);
        }
    }

    private void getOptionData() {
        dbManager = new DBManager( getActivity() );
        options1Items = dbManager.getAllProvince();
        options2Items = dbManager.getAllProvinceCities();
        cityCustomOptions = new OptionsPickerView.Builder( getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String provinceStr = options1Items.get( options1 ).getName();
                String cityStr = options2Items.get( options1 ).get( option2 ).getName();
                postRegion=options2Items.get( options1 ).get( option2 ).getCode();
                // 设置在你组件上的 选取后得到的内容
                post_area_btn.setText( provinceStr + "-" + cityStr );
            }
        } )
                //* 使用系统自带的Color文件 也可用自己的值 但是这里的值要注意 颜色值=（65536*Red)+（256*Green)+(Blue) 不能用R.color的形式
                .setTitleText( "城市选择" )
                .setContentTextSize( 20 )                     //设置滚轮文字大小
                .setDividerColor( Color.GRAY )              //设置分割线的颜色
                .setSelectOptions( 0, 0 )                  //默认选中项
                .setBgColor( Color.WHITE )                // 设置下方选择框的背景颜色
                .setTitleBgColor( getResources().getColor( R.color.home_title_color ) )           // 设置标题处整个背景的背景颜色
                .setTitleColor( Color.WHITE )           // 设置标题颜色
                .setCancelColor( Color.WHITE )         // 设置左边取消按钮颜色
                .setSubmitColor( Color.WHITE )        // 设置右边确定按钮颜色
                .setTextColorCenter( getResources().getColor( R.color.home_title_color ) )   //  设置下方滚轮选中条目的字体颜色
                .isCenterLabel( false ) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                // 只能设为三级  不管显示多少级
                .setBackgroundId( 0x66000000 ) //设置外部遮罩颜色 只能用16进制的方式 这里设置为无颜色 只是透明度修改
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器*/
        cityCustomOptions.setPicker( options1Items, options2Items ); //二级选择器
        /*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/

    }

    @Override
    @OnClick({R.id.post_category_btn, R.id.post_area_btn, R.id.post_commit_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.post_category_btn:
                break;
            case R.id.post_area_btn:
                cityCustomOptions.show();
                break;
            case R.id.post_commit_btn:
                postTitle=post_edit_title.getText().toString();
                userName=post_edit_name.getText().toString();
                phoneNumber=post_edit_mobile.getText().toString();
                postPrice=post_edit_price.getText().toString();
                postArea=post_area_btn.getText().toString();
                postContent=post_edit_content.getText().toString();
                if (uidString.equals( "0" )) {
                    Intent loginIntent = new Intent( getActivity(), LoginActivity.class );
                    startActivity( loginIntent );
                } else {
                    if(TextUtils.isEmpty(postTitle)&&postTitle.length()>5) {
                        ToastUitl.showToastWithImg(getString(R.string.circle_publish_empty),R.drawable.ic_warm);
                    }else{
                        if(TextUtils.isEmpty(postPrice)) {
                            postPrice="0.00";
                        }
                            if(TextUtils.isEmpty(userName)) {
                                ToastUitl.showToastWithImg(getString(R.string.circle_name_empty),R.drawable.ic_warm);
                            }else{
                                if(TextUtils.isEmpty(phoneNumber)) {
                                    ToastUitl.showToastWithImg(getString(R.string.circle_mobile_empty),R.drawable.ic_warm);
                                }else{
                                    if(TextUtils.isEmpty(postArea)) {
                                        ToastUitl.showToastWithImg(getString(R.string.circle_area_empty),R.drawable.ic_warm);
                                    }else{
                                        List<String> imageList=ninePicturesAdapter.getData();
                                        List<String> pathList=new ArrayList<>( );
                                        for(int i=0;i<imageList.size();i++){
                                            String path=imageList.get( i );
                                            if (path.length()>5){
                                                pathList.add( path );
                                            }
                                        }
                                        if (pathList.size() > 0) {
                                            upLoadAllFeedBackImg(pathList);
                                        }else{
                                            if(type.equals( "1" )){
                                                ToastUitl.showToastWithImg(getString(R.string.circle_image_empty),R.drawable.ic_warm);
                                            }else{
                                                handler.sendEmptyMessage( 0 );
                                            }
                                        }
                                    }
                                }
                            }

                    }
                }
                break;
            default:
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    final ProgressDialog pd = new ProgressDialog( getActivity() );
                    String term=String.valueOf(getArguments().getInt(ARG_PARAM1)+2);
                    pd.setMessage( "正在处理，请稍后..." );
                    pd.show();
                    RetrofitManageres.getInstance()
                            .create(AppAPI.class)
                            .AddPostArticle(uidString,term,postTitle,photos_url,postPrice,postRegion,postArea,postContent)
                            .observeOn( AndroidSchedulers.mainThread())
                            .subscribeOn( Schedulers.io())
                            .subscribe(new CommonObserver<CommonResonseBean>() {
                                @Override
                                public void onSuccess(CommonResonseBean value) {
                                    if (value.getCode() == CODE_SUCC) {
                                        post_edit_title.setText( "" );
                                        post_edit_price.setText( "" );
                                        post_edit_content.setText( "" );
                                        Toast.makeText(getActivity(), "供求发布成功", Toast.LENGTH_SHORT).show();
                                        if(mainTabItemListener!=null){
                                            mainTabItemListener.onMainTabItemListener(getArguments().getInt(ARG_PARAM1));
                                        }
                                    }else{
                                        Toast.makeText(getActivity(), "供求发布失败，请稍后再试", Toast.LENGTH_SHORT).show();
                                    }
                                    pd.dismiss();
                                }

                                @Override
                                public void onError(Throwable e) {
                                    super.onError(e);
                                    Toast.makeText(getActivity(), "供求发布失败，请稍后再试", Toast.LENGTH_SHORT).show();
                                    pd.dismiss();
                                }
                            });

                    break;
                default:
                    break;
            }
        }
    };

    private void upLoadAllFeedBackImg(List<String> pathList) {
        final ProgressDialog pd = new ProgressDialog( getActivity() );
        pd.setCanceledOnTouchOutside( false );
        pd.setOnCancelListener( new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                Log.d( TAG, "EMClient.getInstance().onCancel" );
            }
        } );
        pd.setMessage( "正在上传" );
        pd.show();
        QiniuUtils.getUploadManagerInstance();
        //已经上传过的不上传
        final int[] count = {0};
        photos_url=new String[pathList.size()];
        for(String fileName:pathList){
            Bitmap bitmap=BastiGallery.getimage( fileName );
            //bitmap=drawCenterLable(getActivity(),bitmap,"城库货源");
            //byte[] img = BastiGallery.Bitmap2Bytes( bitmap );
            byte[] img=compressBitmap(bitmap,128);
            QiniuUtils.uploadImg( getActivity(), img, QiniuUtils.createImageKey( UserInfoUtils.getPhone( getActivity() ) ), new UpLoadImgCallback() {
                @Override
                public void onSuccess(String imgUrl) {
                    photos_url[count[0]]=imgUrl;
                    count[0]++;
                    Log.e( "111111111111", "imgUrl = " + imgUrl );
                    if(count[0]==pathList.size()){
                        pd.dismiss();
                        handler.sendEmptyMessage( 0 );
                    }
                }

                @Override
                public void onFailure() {
                    count[0]++;
                    if(count[0]==pathList.size()){
                        pd.dismiss();
                        handler.sendEmptyMessage( 0 );
                    }
                }
            } );
        }
    }


    public static byte[] compressBitmap(Bitmap bitmap,float size){
        if(bitmap==null||BastiGallery.Bitmap2Bytes(bitmap).length<=size*1024){
            return null;//如果图片本身的大小已经小于这个大小了，就没必要进行压缩
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality=100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);//如果签名是png的话，则不管quality是多少，都不会进行质量的压缩
        while (baos.toByteArray().length / 1024f>size) {
            quality=quality-4;// 每次都减少4
            baos.reset();// 重置baos即清空baos
            if(quality<=0){
                break;
            }
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            //Log.e(TAG,"------质量--------"+baos.toByteArray().length/1024f);
        }
        return baos.toByteArray();
    }

    /*
   添加全屏斜着45度的文字
   */
  public static Bitmap drawCenterLable(Context context, Bitmap bmp, String text) {
    float scale = context.getResources().getDisplayMetrics().density;
    //创建一样大小的图片
    Bitmap newBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888);
    //创建画布
    Canvas canvas = new Canvas(newBmp);
    canvas.drawBitmap(bmp, 0, 0, null);  //绘制原始图片
    canvas.save();
    canvas.rotate(45); //顺时针转45度
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.argb(50, 255, 255, 255)); //白色半透明
    paint.setTextSize(100*scale);
    paint.setDither(true);
    paint.setFilterBitmap(true);
    Rect rectText = new Rect();  //得到text占用宽高， 单位：像素
    paint.getTextBounds(text, 0, text.length(), rectText);
    double beginX = (bmp.getHeight()/2 - rectText.width()/2) * 1.4;  //45度角度值是1.414
    double beginY = (bmp.getWidth()/2 - rectText.width()/2) * 1.4;
    canvas.drawText(text, (int)beginX, (int)beginY, paint);
    canvas.restore();
    return newBmp;
  }

    /**
     * 开启图片选择器
     */
    private void choosePhoto() {
        ImgSelConfig config = new ImgSelConfig.Builder( loader )
                // 是否多选
                .multiSelect( true )
                // 确定按钮背景色
                .btnBgColor( Color.TRANSPARENT )
                .titleBgColor( ContextCompat.getColor( getActivity(), R.color.main_color ) )
                // 使用沉浸式状态栏
                .statusBarColor( ContextCompat.getColor( getActivity(), R.color.main_color ) )
                // 返回图标ResId
                .backResId( R.drawable.ic_arrow_back )
                .title( "图片" )
                // 第一个是否显示相机
                .needCamera( true )
                // 最大选择图片数量
                .maxNum( 9 - ninePicturesAdapter.getPhotoCount() )
                .build();
        ImgSelActivity.startActivity( this, config, REQUEST_CODE );
    }

    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            ImageLoaderUtils.display( context, imageView, path );
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra( ImgSelActivity.INTENT_RESULT );
            if (ninePicturesAdapter != null) {
                ninePicturesAdapter.addAll( pathList );
            }
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach( activity );
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
